package com.lagou.monitor;

import com.lagou.model.TPData;

import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class TPDataMonitor {

    public ConcurrentLinkedQueue<TPData> queueA;
    public ConcurrentLinkedQueue<TPData> queueB;
    public ConcurrentLinkedQueue<TPData> queueC;

    private TPDataMonitor(){
        queueA = new ConcurrentLinkedQueue<TPData>();
        queueB = new ConcurrentLinkedQueue<TPData>();
        queueC = new ConcurrentLinkedQueue<TPData>();
    }

    //内部静态类--无参单例模式
    private static class TPDataMonitorHolder {
        private static final TPDataMonitor sInstance = new TPDataMonitor();
    }

    public static TPDataMonitor getInstance(){
        return TPDataMonitorHolder.sInstance;
    }

    public void clearQueue(Queue<TPData> queue){
        this.clearQueue(queue, 60*1000);
    }

    public void clearQueue(Queue<TPData> queue, long expireTimeMillis){
        long startTime = System.currentTimeMillis() - expireTimeMillis;
        try{
            while (startTime > queue.peek().getTimeStamp()){
                TPData pollData = queue.poll();
                long dataTimeStamp = pollData.getTimeStamp();
                System.out.println("data expired, timestamp is " + dataTimeStamp
                        + ", current time is " + startTime + ", expired for " +
                        (startTime - dataTimeStamp)/1000 + " seconds");
            }
        }catch (Exception e){
//            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    public void outPutQueueStats(Queue<TPData> queue, long starTime, String MethodName){

        //按时间顺序从queue中取出数据，放入新的list，里面只存调用耗时数据。
        ArrayList<Long> list = new ArrayList();
        for (TPData tpData : queue) {
            if(tpData.getTimeStamp() > starTime){
                list.add(tpData.getDuration());
            }
        }

        //先排序，再直接按下标取
        list.sort(Long::compareTo);
        double tp90IndexD = list.size() * 0.9;
        double tp99IndexD = list.size() * 0.99;

        if(!list.isEmpty()){
            System.out.println( MethodName + "--tp90: " + list.get((int)Math.ceil(tp90IndexD)));
            System.out.println( MethodName + "--tp99: " + list.get((int)Math.ceil(tp99IndexD)));
        }

        //计算完成后就把1min外的数据清除，不单独开线程处理了
        clearQueue(queue);
    }

    public void calcTP90andTp99inRecentMin(){
        long stopTime = System.currentTimeMillis();
        long starTime = stopTime - 60*1000;

        outPutQueueStats(queueA, starTime, "MethodA");
        outPutQueueStats(queueB, starTime, "MethodB");
        outPutQueueStats(queueC, starTime, "MethodC");
    }
}
